package com.epalmpay.util;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Random;

/**
 * Created by lifayi on 2017/10/13.
 */
@Service
public class FileUpload {

    @Value("${fileLocalPath}")
    private String fileLocalPath;

    @Value("${fileServerURL}")
    private String fileServerURL;

    @Value("${accessFileURL}")
    private String accessFileURL;

    public String upload(MultipartFile file, String path) {
        String tmpPath = fileLocalPath + path;
        String name = file.getOriginalFilename();
        int a = -1;
        try {
            String extName = "";
            if (name.lastIndexOf(".") >= 0) {
                extName = name.substring(name.lastIndexOf("."));
            }
            name = new Date().getTime() + getRandNum(6).toString() + extName;
            File f = new File(tmpPath, name);
            FileUtils.copyInputStreamToFile(file.getInputStream(), f);
            a = postHttp(fileServerURL, "file" + path, f);
        } catch (Exception e) {
            e.printStackTrace();
            return "failed";
        }
        if (a == -1) {
            return "failed";
        } else {
            return accessFileURL + path + name;
        }
    }

    public String upload(String base64InputStr,String fileName, String path) {

        byte[] inputStrByte = Base64Utils.decode(base64InputStr);
        InputStream is = new ByteArrayInputStream(inputStrByte);

        String tmpPath = fileLocalPath + path;
        String name = fileName;
        int a = -1;
        try {
            String extName = "";
            if (name.lastIndexOf(".") >= 0) {
                extName = name.substring(name.lastIndexOf("."));
            }
            name = new Date().getTime() + getRandNum(6).toString() + extName;
            File f = new File(tmpPath, name);
            FileUtils.copyInputStreamToFile(is, f);
            a = postHttp(fileServerURL, "file" + path, f);
        } catch (Exception e) {
            e.printStackTrace();
            return "failed";
        }
        if (a == -1) {
            return "failed";
        } else {
            return accessFileURL + path + name;
        }
    }

    private int postHttp(String url, String path, File file) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url);
        MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
        mEntityBuilder.addBinaryBody("file", file);
        mEntityBuilder.addTextBody("path", path);
        httppost.setEntity(mEntityBuilder.build());
        HttpResponse resp = httpClient.execute(httppost);
        int code = resp.getStatusLine().getStatusCode();
        if (200 == code) {
            return 0;
        } else {
            return -1;
        }
    }

    private char[] getRandNum(int n) {
        char[] rand = new char[n];
        String str = "23456789qwertyuipkjhgfdsacvbnmQWERTYUPLKJHGFDSACVBNM";
        for (int i = 0; i < n; i++) {
            Random rd = new Random();
            int index = rd.nextInt(str.length());
            rand[i] = str.charAt(index);
        }
        return rand;
    }
}